package com.up.stores.controller;

import com.up.stores.service.ICartService;
import com.up.stores.until.JsonResult;
import com.up.stores.vo.CartVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@Api(tags="购物车模块")
@RequestMapping("carts")
@RestController
public class CartController extends BaseController {
    @Autowired
    private ICartService cartService;

    @ApiOperation(value="添加购物车")
    @PostMapping("add_to_cart")
    public JsonResult<Void> addCart(Integer proId,
                                      Integer amount,
                                      HttpSession session) {
        // 调用业务对象执行添加到购物车
        cartService.addCart(getuidFromSession(session),getTypeFromSession(session),
                proId, amount,getUsernameFromSession(session));
        // 返回成功
        return new JsonResult<>(OK);
    }

    @ApiOperation(value="购物车删除")
    @DeleteMapping("delete_to_cart")
    public JsonResult<Void> deleteCart(Integer cartId) {
        // 调用业务对象执行从购物车删除
        cartService.deleteCart(cartId);
        // 返回成功
        return new JsonResult<>(OK);
    }

    @ApiOperation(value="获取当前用户购物车信息")
    @GetMapping({"/"})
    public JsonResult<List<CartVO>> getVOByUidAndType(HttpSession session) {
        // 从Session中获取uid和type
        Integer uid = getuidFromSession(session);
        String type = getTypeFromSession(session);
        // 调用业务对象执行查询数据
        List<CartVO> data = cartService.getVOByUidAndType(uid,type);
        // 返回成功与数据
        return new JsonResult<List<CartVO>>(OK, data);
    }


    @ApiOperation(value="购物车中该商品数量+1")
    @PutMapping("num/add")
    public JsonResult<Integer> addNum(Integer cartId, HttpSession session) {
        // 从Session中获取username
        Integer data = cartService.addNum(cartId,getUsernameFromSession(session));
        // 返回成功
        return new JsonResult<Integer>(OK, data);
    }

    @ApiOperation(value="购物车中该商品数量-1")
    @PutMapping("num/reduce")
    public JsonResult<Integer> reduceNum(Integer cartId, HttpSession session) {
        // 从Session中获取uid和username
        Integer data = cartService.reduceNum(cartId,getUsernameFromSession(session));
        // 返回成功
        return new JsonResult<Integer>(OK, data);
    }

    @ApiOperation(value="根据若干个购物车数据id查询详情的列表")
    @GetMapping("list")
    public JsonResult<List<CartVO>> getVOByCartIds(Integer[] cartIds) {
        // 调用业务对象执行查询数据
        List<CartVO> data = cartService.getVOByCartIds(cartIds);
        // 返回成功与数据
        return new JsonResult<>(OK, data);
    }
}